package ch06.servlet;

import ch06.action.BaseAction;
import ch06.action.UserAction;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("*.action")
public class DispatcherServlet extends HttpServlet {
    public Map<String, BaseAction> map=new HashMap<>();

    public void init(){
        System.out.println("start");
        UserAction userAction=new UserAction();
         map.put("/user",userAction);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html; charset=UTF-8");
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        String url=req.getRequestURI();
        url = url.substring(url.lastIndexOf("/"),url.lastIndexOf("."));
        BaseAction action = map.get(url);
        action.execute(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
